package com.mjf.io.properties;

import org.junit.Test;

import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class PropertiesWithFile {

    /**
     * 读取 Properties 配置文件
     * @throws IOException
     */
    @Test
    public void readProp() throws IOException {
        Properties prop = new Properties();

        // 获取配置文件路径
        String propPath = PropertiesWithFile.class.getResource("/mysql.properties").getPath();

        prop.load(new FileReader(propPath));

        // 把 k-v 显示到控制台
        prop.list(System.out);

        // 获取对应 key 的 value
        String host = prop.getProperty("host");
        String user = prop.getProperty("user");
        String password = prop.getProperty("password");

        System.out.println();
        System.out.println("域名:" + host);
        System.out.println("用户名:" + user);
        System.out.println("密码:" + password);
    }

    /**
     * 将配置信息存储到 Properties 配置文件
     * @throws IOException
     */
    @Test
    public void writeProp() throws IOException {
        Properties prop = new Properties();

        String propPath = "D:\\coding\\idea\\java-stu\\src\\main\\resources\\mysql2.properties";

        prop.setProperty("charset", "utf8");
        prop.setProperty("user", "汤姆");   // 注意保存时，是中文的 unicode 码值
        prop.setProperty("pwd", "888888");

        // 将 k-v 存储文件中
        prop.store(new FileOutputStream(propPath), "mysql info");
    }

}
